//
//  OrderListViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/27.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit
import MapKit

class OrderListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PayViewDelegate {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var tableView: UITableView!
    
    var orderData: NSArray?
    
    var refreshControl: UDRefreshControl!
    
    var emptyView: UILabel!
    var payView: PayView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "订单"
        
//        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
//        navBar.barTintColor = themeColor2
//        navBar.barStyle = .black
//        navBar.tintColor = UIColor.white
        
        navigationController?.navigationBar.barStyle = .black
        navigationController?.navigationBar.barTintColor = themeColor2
        navigationController?.navigationBar.tintColor = UIColor.white
        
//        let navItem = UINavigationItem(title: "订单")
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(OrderListViewController.goBack))
//        navBar.pushItem(navItem, animated: true)
        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.groupTableViewBackground
        view.addSubview(tableView)
        
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -64, width: view.frame.width, height: 64))
        tableView.addSubview(refreshControl)
        
        emptyView = UILabel(frame: CGRect(x: 16, y: 64, width: view.frame.width - 32, height: 64))
        emptyView.font = UIFont.systemFont(ofSize: 14)
        emptyView.textAlignment = .center
        emptyView.text = "暂无数据"
        emptyView.textColor = UIColor.lightGray
        tableView.addSubview(emptyView)
        
//        view.addSubview(navBar)
        
        payView = PayView(frame: view.frame)
        payView.delegate = self
        view.addSubview(payView)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        refreshList()
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y < -150{
            if refreshControl.state == .normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            if refreshControl.state == .ready{
                refreshControl.endRefresh()
            }
            
        }
        
        
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if refreshControl.state == .ready{
            refreshList()
        }
    }
    
    func refreshList(){
        refreshControl.beginRefresh()
        var insert = tableView.contentInset
        insert.top += 64
        tableView.contentInset = insert
        
        var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=Goods&a=queryOrder")!)
        req.httpMethod = "POST"
        req.httpBody = "month=1".data(using: .utf8)
        
        URLSession.shared.dataTask(with: req) { (data:Data?, re:URLResponse?, er:Error?) in
            DispatchQueue.main.async {
                self.refreshControl.endRefresh()
                var insert = self.tableView.contentInset
                insert.top -= 64
                UIView.animate(withDuration: 0.3, animations: {
                    self.tableView.contentInset = insert
                })
            }
            do{
                if er != nil{
                    throw er!
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.orderData = jsonObj?.object(forKey: "data") as? NSArray
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    self.emptyView.alpha = 1
                    if self.orderData != nil{
                        if self.orderData!.count > 0{
                            self.emptyView.alpha = 0
                        }
                    }
                }
            }catch let ex{
                print(ex)
            }
        }.resume()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderData?.count ?? 0
//        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 170
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        
        cell.selectionStyle = .none
        cell.backgroundColor = UIColor.clear
        
        let cardView = UIView(frame: CGRect(x: 16, y: 5, width: view.bounds.width - 32, height: 156))
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        cell.addSubview(cardView)
        
        let shopNameLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 48 - 28 - 16, height: 28))
//        shopNameLabel.textColor = UIColor.lightGray
        shopNameLabel.font = UIFont.systemFont(ofSize: 14)
        cardView.addSubview(shopNameLabel)
        
        let mapBtn = UIButton(frame: CGRect(x: cardView.bounds.width - 28 - 16, y: 8, width: 28, height: 28))
        mapBtn.setImage(#imageLiteral(resourceName: "location"), for: .normal)
        mapBtn.imageView?.contentMode = .scaleAspectFit
        cardView.addSubview(mapBtn)
        mapBtn.addTarget(self, action: #selector(OrderListViewController.gotoMap(btn:)), for: .touchUpInside)
        
        let line = UIView(frame: CGRect(x: 16, y: 44, width: cardView.bounds.width-32, height: 0.5))
        line.backgroundColor = UIColor.lightGray
        cardView.addSubview(line)
        
        let icon = UIImageView(frame: CGRect(x: 16, y: 48, width: 50, height: 63))
        icon.image = #imageLiteral(resourceName: "doc_icon")
        cardView.addSubview(icon)
        
        let fileNameLabel = UILabel(frame: CGRect(x: 16 + 50 + 8, y: 48, width: cardView.bounds.width - 16 - 50 - 8, height: 30))
        fileNameLabel.numberOfLines = 0
        fileNameLabel.font = UIFont.systemFont(ofSize: 14)
        cardView.addSubview(fileNameLabel)
        
        let fileInfoLabel = UILabel(frame: CGRect(x: 16 + 50 + 8, y: 48 + 31, width: cardView.bounds.width - 16 - 50 - 8, height: 30))
        fileInfoLabel.numberOfLines = 0
        fileInfoLabel.font = UIFont.systemFont(ofSize: 14)
        fileInfoLabel.textColor = UIColor.lightGray
        cardView.addSubview(fileInfoLabel)
        
        let line2 = UIView(frame: CGRect(x: 16, y: 44 + 63 + 8, width: cardView.bounds.width-32, height: 0.5))
        line2.backgroundColor = UIColor.lightGray
        cardView.addSubview(line2)
        
        let priceLabel = UILabel(frame: CGRect(x: 16, y: 44 + 63 + 8 + 4, width: cardView.bounds.width/2, height: 28))
        priceLabel.font = UIFont.systemFont(ofSize: 14)
        priceLabel.textColor = UIColor.lightGray
        cardView.addSubview(priceLabel)
        
        
        let actBtn2 = UIButton(frame: CGRect(x: cardView.bounds.width - 64 - 16, y: 44 + 63 + 8 + 4, width: 64, height: 28))
        actBtn2.tag = indexPath.row
        actBtn2.setTitleColor(UIColor.white, for: .normal)
        actBtn2.backgroundColor = themeColor1
        actBtn2.layer.cornerRadius = 4
        actBtn2.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cardView.addSubview(actBtn2)
        actBtn2.addTarget(self, action: #selector(OrderListViewController.goPay(btn:)), for: .touchUpInside)
        
        let actBtn1 = UIButton(frame: CGRect(x: cardView.bounds.width - 64 - 70 - 16, y: 44 + 63 + 8 + 4, width: 64, height: 28))
        actBtn1.tag = indexPath.row
        actBtn1.setTitleColor(UIColor.lightGray, for: .normal)
        //        actBtn1.backgroundColor = themeColor1
        actBtn1.layer.cornerRadius = 4
        actBtn1.layer.borderColor = UIColor.lightGray.cgColor
        actBtn1.layer.borderWidth = 1
        actBtn1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cardView.addSubview(actBtn1)
        actBtn1.addTarget(self, action: #selector(OrderListViewController.cancelOrder(btn:)), for: .touchUpInside)
        
        actBtn2.setTitle("支付", for: .normal)
        
        let orderItem = orderData?.object(at: indexPath.row) as? NSDictionary
        
        
        shopNameLabel.text = orderItem?.object(forKey: "nickname") as? String ?? "商家名称"
        fileNameLabel.text = orderItem?.object(forKey: "sourcefilename") as? String ?? "file"
        
        var subInfo = ""
        
        subInfo += "\(orderItem?.object(forKey: "pnum") as? String ?? "0")页"
        subInfo += " x \(orderItem?.object(forKey: "goods_number") as? String ?? "0")份"
        
        var type: FCPrintPaperType?
        var paperType = orderItem?.object(forKey: "bsingle")
        if paperType != nil {
            type = .blackWhiteSingle
        }else{
            paperType = orderItem?.object(forKey: "bdouble")
            type = .blackWhiteDouble
        }
        if paperType == nil {
            paperType = orderItem?.object(forKey: "csingle")
            type = .colorSingle
        }
        if paperType == nil {
            paperType = orderItem?.object(forKey: "cdouble")
            type = .colorDouble
        }
        
        if type != nil{
            switch type! {
            case .blackWhiteSingle:
                subInfo += " 黑白 单面"
                break
            case .blackWhiteDouble:
                subInfo += " 黑白 双面"
                break
            case .colorSingle:
                subInfo += " 彩色 单面"
                break
            case .colorDouble:
                subInfo += " 彩色 双面"
                break
            }
        }
        
        
        
        fileInfoLabel.text = subInfo
        priceLabel.text = "￥ \(orderItem?.object(forKey: "total_price") as? String ?? "0.00")"
        
        actBtn1.setTitle("取消", for: .normal)
        
        let payStatus = orderItem?.object(forKey: "pay_status") as? String ?? "0"
        if payStatus == "1" {
            actBtn1.alpha = 0
            actBtn2.layer.borderColor = UIColor.lightGray.cgColor
            actBtn2.layer.borderWidth = 1
            actBtn2.backgroundColor = UIColor.white
            actBtn2.setTitle("已支付", for: .normal)
            actBtn2.setTitleColor(UIColor.lightGray, for: .normal)
        }
        
        return cell
    }
    
    func goPay(btn: UIButton){
        let index = btn.tag
        print("pay \(index)")
        
        let orderItem = orderData?.object(at: index) as? NSDictionary
        
        let payStatus = orderItem?.object(forKey: "pay_status") as? String ?? "0"
        
        if payStatus != "1"{
            payView.openView(orderItem?.object(forKey: "total_price") as? String, orderID: orderItem?.object(forKey: "or_num") as? String)
        }
        
        
    }
    
    func payView(_ payView: PayView, didSuccessPay data: Any?) {
        self.refreshList()
    }
    
    func cancelOrder(btn: UIButton){
        let index = btn.tag
        print("cancel \(index)")
        
        let alert = UIAlertController(title: "取消订单?", message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "取消订单", style: .destructive, handler: { (action) in
            let orderItem = self.orderData?.object(at: index) as? NSDictionary
            let ornum = orderItem?.object(forKey: "or_num") as? String
            if ornum != nil{
                var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=deleteorder")!)
                req.httpMethod = "POST"
                req.httpBody = "ornum=\(ornum!)".data(using: .utf8)
                URLSession.shared.dataTask(with: req, completionHandler: { (data, _, err) in
                    do{
                        if err != nil{
                            throw err!
                        }
                        
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let reCode = jsonObj?.object(forKey: "code") as? Int
                        if reCode == 200{
                            DispatchQueue.main.async {
                                self.refreshList()
                            }
                        }else{
                            let alert = UIAlertController(title: "取消失败", message: "请尽快联系客服", preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                            }
                        }
                    }catch let ex{
                        print(ex)
                        let alert = UIAlertController(title: "取消失败", message: "请尽快联系客服", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
                }).resume()
            }
        }))
        alert.addAction(UIAlertAction(title: "返回", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    func goBack(){
        dismiss(animated: true, completion: nil)
    }
    
    func gotoMap(btn: UIButton){
        let index = btn.tag
        print("map \(index)")
        
        let orderItem = orderData?.object(at: index) as? NSDictionary
        let shopname = orderItem?.object(forKey: "nickname") as? String
        let location = orderItem?.object(forKey: "location") as? String
        
        let locaInfo = location?.components(separatedBy: ",")
        if locaInfo != nil{
            if locaInfo!.count > 1{
                let longitude = locaInfo![0]
                let latitude = locaInfo![1]
                let latitudeValue = Double(latitude)
                let longitudeValue = Double(longitude)
                if latitudeValue != nil && longitudeValue != nil {
                    let location = CLLocationCoordinate2D(latitude: latitudeValue!, longitude: longitudeValue!)
                    let map = MKMapItem(placemark: MKPlacemark(coordinate: location, addressDictionary: nil))
                    map.name = shopname
                    MKMapItem.openMaps(with: [map], launchOptions: [MKLaunchOptionsMapCenterKey: true])
                }
            }
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
